/*

This file is part of Ext JS 4

Copyright (c) 2011 Sencha Inc

Contact:  http://www.sencha.com/contact

GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.

If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.

*/
Ext.define('Writer.Form', {
    extend: 'Ext.form.Panel',
    alias: 'widget.writerform',

    requires: ['Ext.form.field.Text'],

    initComponent: function(){
        this.addEvents('create');
        Ext.apply(this, {
            activeRecord: null,
            iconCls: 'icon-user',
            frame: true,
            title: 'ABM USUARIOS',
            defaultType: 'textfield',
            bodyPadding: 5,
            fieldDefaults: {
                anchor: '100%',
            },
            items: [{
                fieldLabel: 'Id',
                name: 'id',
                type: 'int',
                fieldCls : 'x-item-disabled',
            },{
                fieldLabel: 'Nombre Usuario',
                name: 'nombreUsuario',
                 //fieldCls : 'x-item-disabled',
                allowBlank: false
               
				
            },{
                fieldLabel: 'Password',
                name: 'password1',
				inputType: 'password',
                //allowBlank: false
            },{
                fieldLabel: 'Nombre',
                name: 'nombre',
            }, {
                fieldLabel: 'Apellido',
                name: 'apellido',
            }, {
                fieldLabel: 'Telefono',
                name: 'telefono',
                type: 'int',
            }, {
                fieldLabel: 'Nº Documento',
                name: 'nroDocumento',
                type: 'int',
            },{
                fieldLabel: 'Email',
                name: 'email',
                allowBlank: false,
                vtype: 'email'
            }],
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    iconCls: 'icon-rol',
                    itemId: 'rol',
                    text: 'Roles...',
                    disabled: true,
                    scope: this, 
                    handler: this.onRol
                }]}, {
				weight: 1,
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    iconCls: 'icon-save',
                    itemId: 'save',
                    text: 'Guardar',
                    disabled: true,
                    scope: this, 
                    handler: this.onSave
                }, {
                    iconCls: 'icon-user-add',
                    itemId: 'create',
                    text: 'Crear',
                    scope: this,
                    handler: this.onCreate
                }, {
                    iconCls: 'icon-reset',
                    text: 'Reset',
                    scope: this,
                    handler: this.onReset
                }, {
                    iconCls: 'icon-user-delete',
                    itemId: 'delete',
                    disabled: true,
                    scope: this, 
                    text: 'Eliminar',
                    scope: this,
                    handler: this.onDelete
                }]
            }]
        });
        this.callParent();
    },

    setActiveRecord: function(record){
        this.activeRecord = record;
        if (record) {
            this.down('#save').enable();
            this.down('#delete').enable();
            this.down('#rol').enable();
            this.down('#create').disable(); 
                       
            this.getForm().loadRecord(record);
        } else {
            this.down('#save').disable();
            this.down('#delete').disable();
            this.down('#rol').disable();
            this.down('#create').enable(); 
            this.getForm().reset();
        }
    },

    onSave: function(){
        var form = this.getForm();

                    form.submit({
                        
                        url: '/modificarUsuarios',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Usuario modificado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido modificar el usuario');
                        }
                    });

	
        /*if (form.isValid()) {
            this.fireEvent('create', this, form.getValues());
            form.reset();
        }*/

    },

    onCreate: function(){
        var form = this.getForm();

                    form.submit({
                        
                        url: '/crearUsuarios',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Usuario creado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido crear el usuario');
                        }
                    });

	
        /*if (form.isValid()) {
            this.fireEvent('create', this, form.getValues());
            form.reset();
        }*/

    },

    onDelete: function(){ 
        var form = this.getForm();

                    form.submit({
                        
                        url: '/eliminarUsuarios',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
                           Ext.Msg.alert('Usuario eliminado satisfactoriamente');
                           form.reset();
                        },
                        failure: function(form, action) {
                            Ext.Msg.alert('Error - No se ha podido eliminar el usuario');
                        }
                    });

	
        /*if (form.isValid()) {
            this.fireEvent('create', this, form.getValues());
            form.reset();
        }*/

    },
	onRol: function(){
			var form = this.getForm();
			this.fireEvent('create', form.getValues(true));
            
	},

    onReset: function(){
        this.setActiveRecord(null);
        this.getForm().reset();
    }
    
    
    
});


Ext.define('Writer.Grid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.writergrid',

    requires: [
        'Ext.grid.plugin.CellEditing',
        'Ext.form.field.Text',
        'Ext.toolbar.TextItem'
    ],

    initComponent: function(){

        this.editing = Ext.create('Ext.grid.plugin.CellEditing');

        Ext.apply(this, {
            iconCls: 'icon-grid',
            frame: true,
            plugins: [this.editing],
            dockedItems: [{ //toolbar para filtrado	falta
                weight: 1,
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    iconCls: 'icon-refresh',
                    text: 'Actualizar',
                    scope: this,
                    handler: this.onRefresh
                }]
            }],
            columns: [{
                text: 'Id',
                width: 30,
                sortable: true,
                dataIndex: 'id'
            },{
                header: 'Nombre Usuario',
                width: 90,
                sortable: true,
                dataIndex: 'nombreUsuario',

            },{
                header: 'Nombre',
                flex: 1,
                sortable: true,
                dataIndex: 'nombre',

            }, {
                header: 'Apellido',
                flex: 1,
                sortable: true,
                dataIndex: 'apellido',

            },{
                text: 'Telefono',
                sortable: true,
                width: 60,              
                dataIndex: 'telefono'
            },{
                text: 'Nº Documento',
                flex: 1,
                sortable: true,
                dataIndex: 'nroDocumento'
            }, {
                header: 'Email',
                width: 130,
                sortable: true,
                dataIndex: 'email',

            },{
                header: 'Fecha Creacion',
                width: 100,
                dataIndex: 'fecha',

            }]
        });
        this.callParent();
        this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
    },
    

    onRefresh: function(){
		this.store.load();
    }
});

Ext.define('Writer.Person', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'id',
        type: 'int',
        useNull: true
    },{
        name: 'nroDocumento',
        type: 'int',
    },{
        name: 'telefono',
        type: 'int',
    }, 'email', 'nombre', 'apellido', 'nombreUsuario', 'fecha'],
    validations: [{
        type: 'length',
        field: 'email',
        min: 1
    }, {
        type: 'length',
        field: 'first',
        min: 1
    }, {
        type: 'length',
        field: 'last',
        min: 1
    }, {
        type: 'length',
        field: 'nombreUsuario',
        min: 1
    }]
});



Ext.require([
    'Ext.data.*',
    'Ext.tip.QuickTipManager',
    'Ext.window.MessageBox',
    
    'Ext.tab.*',
    'Ext.window.*',
    'Ext.tip.*',
    'Ext.layout.container.Border',
    
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet'
]);


Ext.define('modeloRol', {
    extend: 'Ext.data.Model',
    fields: [ {
			name: 'nombreRol'
		}]
});

Ext.onReady(function(){
    Ext.tip.QuickTipManager.init();
    
    var storeRol = Ext.create('Ext.data.Store', {
        model: 'modeloRol',
        autoLoad: true,
        proxy: {
            type: 'ajax',
            url: '/listarRoles',
            reader: {
                type: 'json',
                successProperty: 'success',
                root: 'data',
                messageProperty: 'message'
            },
            writer: {
                type: 'json',
                writeAllFields: false,
                root: 'data'
            },

        }        
        
    });
    
    var store = Ext.create('Ext.data.Store', {
        model: 'Writer.Person',
        autoLoad: true,
        autoSync: true,
        proxy: {
            type: 'ajax',
            url: '/listarUsuarios',
            reader: {
                type: 'json',
                successProperty: 'success',
                root: 'data',
                messageProperty: 'message'
            },
            writer: {
                type: 'json',
                writeAllFields: false,
                root: 'data'
            },

        },
        listeners: {
            write: function(proxy, operation){
                if (operation.action == 'destroy') {
                    main.child('#form').setActiveRecord(null);
                }
                Ext.example.msg(operation.action, operation.resultSet.message);
            }
        },
        
        sorters: [{
            property: 'id',
            direction: 'ASC'
        }]        
    });
    

   /* var main = Ext.create('Ext.container.Container', {

        renderTo: 'comboUsuarios',
	
        items: [{
            itemId: 'form',
            xtype: 'writerform',
            width: 400,
            y: 40,
            x: 800,
            listeners: {
                create: function(form, data){
                    store.insert(0, data);
                }
            }
        }, {
            itemId: 'grid',
            xtype: 'writergrid',
            title: 'Lista de Usuarios del Sistema',
			y: -270,
			x: 60,
            flex: 1,        
            width: 680,
            height: 380,

            store: store,
            listeners: {
                selectionchange: function(selModel, selected) {
                    main.child('#form').setActiveRecord(selected[0] || null);
                }
            }
        }]
    });*/
    
			win = Ext.create('widget.panel', {
				renderTo: 'comboUsuarios',
                width: 1000,
                height: 360,
                layout: 'border',
                bodyStyle: 'padding: 5px;',
				y: 20,
				x: 20,
                items: [{
                    region: 'west',
					xtype: 'writerform',
					itemId: 'form',
					width: 300,

					listeners: {
						create: function(data){
								data = extraer(data, 'id=', '&');
							    //Ext.Msg.alert(data);
							    							
                            	win2 = Ext.create('widget.window', {
								height: 160,
								width: 300,
								iconCls: 'icon-rol',
								//x: 450,
								//y: 450,
								title: 'ADMINISTRAR ROLES',
								closable: true,
								plain: true,
								layout: 'fit',
								items: [floater = Ext.create('Ext.Component', {
									xtype: 'component',
									floating: {
										shadow: false
									},
									height: 50,
									width: 50,
									x: 175,
									y: 75
								}), formPanel = Ext.widget('form', {

								frame: true,
							
								bodyPadding: 10,
								bodyBorder: true,
								
								items: [{
									xtype: 'textfield',
									name: 'id_usuario',
									fieldLabel: 'Id Usuario',
									allowBlank: false,
									fieldCls : 'x-item-disabled',
									value: data,
								   
								}, {
									xtype: 'combobox',
									name: 'roles',
									fieldLabel: 'Roles',
									multiSelect: true,
									displayField: 'nombreRol',
									store: storeRol,
								   
								}],

								dockedItems: [{
									xtype: 'container',
									dock: 'bottom',
									layout: {
										type: 'hbox',
										align: 'middle'
									},
									padding: '5 5 5',

									items: [{
										xtype: 'button',
										formBind: true,
										disabled: true,
										iconCls: 'icon-save',
										text: 'Confirmar',
										width: 80,
										handler: function() {
												var form = this.up('form').getForm();
												form.submit({
													url: '/asignarRol',	
													params: {
															submit: 'submit'
													},
													method: "post",
													success: function(form, action) {			
														Ext.Msg.alert('Rol asignado satisfactoriamente');
													},
													failure: function(form, action) {
														Ext.Msg.alert('Error al asiganr el rol');
													}		
													
												});
											
										}
									}]
								}]
							}),{
									border: false
								}]
							});
					
					win2.show();

						}
					}
				}, {
                    region: 'center',
					xtype: 'writergrid',            
					itemId: 'grid',
					title: 'LISTADO USUARIOS ',

					flex: 1,        
					width: 680,
					height: 380,

					store: store,
					listeners: {
						selectionchange: function(selModel, selected) {
							win.child('#form').setActiveRecord(selected[0] || null);
						}
					}
				}		
				]
            });
            win.show()
    
});

    function extraer(texto, etqini, etqfin)
	{
		var ind0, ind1, parte ="";
		ind0 = texto.indexOf(etqini);
		if (ind0 >=0)
		{
			ind1 = texto.indexOf(etqfin);
		if (ind1>ind0)
			parte = texto.substring(ind0+etqini.length, ind1);
		}
		return parte;
	}

